import React, { useEffect, useState } from 'react'
import { Form, Input, InputNumber, Popconfirm, Table, Typography, Button, Switch, Modal } from 'antd';
import axios from "axios";
import api from '../../server/Api';
import './CustomerManagement.css'


export default function CustomerManagement() {
  const [dataSource, setDataSource] = useState([]);
  const [loading, setLoading] = useState(true);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const edit = (userId) => {
    setIsModalOpen(true);
    axios.post(`${api}/selectUserById`, { userId }).then(response => {
      form.setFieldsValue({
        userId:response.data.data.userId,
        username: response.data.data.username,
        address: response.data.data.address,
        createTime: new Date(response.data.data.createTime).getFullYear() + '-' + (new Date(response.data.data.createTime).getMonth() + 1) + '-' + new Date(response.data.data.createTime).getDate(),
        state: response.data.data.state == 1 ? '正常' : '冻结',
        tel: response.data.data.tel
      })
    }).catch(err => {
      console.log(err)
    })
  };
  const handleOk = () => {
    setIsModalOpen(false);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  const columns = [
    {
      title: '编号',
      dataIndex: 'userId',
      key: 'userId',
    },
    {
      title: '姓名',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '水表安装地址',
      dataIndex: 'address',
      key: 'address',
    },
    {
      title: '电话',
      dataIndex: 'tel',
      key: 'tel',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (_, record) => {
        record.createTime = new Date()
        return (
          <>
            {record.createTime.getFullYear() + '-' + (record.createTime.getMonth() + 1) + '-' + record.createTime.getDate()}
          </>
        )
      }
    },
    {
      title: '状态',
      dataIndex: 'state',
      render: (_, record) => {
        if (record.state == 1) {
          return (
            <>
              <Switch checkedChildren="冻结" unCheckedChildren="正常" onChange={() => changeState(record.state, record.userId)} />
            </>
          )
        } else {
          return (
            <>
              <Switch checkedChildren="冻结" unCheckedChildren="正常" onChange={() => changeState(record.state, record.userId)} defaultChecked />
            </>
          )
        }
      }
    },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (_, record) => {
        return (
          <>
            <Typography.Link onClick={() => edit(record.userId)}>
              修改
            </Typography.Link>
            <Typography.Link onClick={() => Remove(record.userId)}>
              删除
            </Typography.Link>
          </>
        );
      },
    },
  ];

  // 修改账号状态
  const changeState = (state, userId) => {
    axios.post(`${api}/changeState`, { state, userId }).then((response) => {
      getUserInfo()
    }).catch(err => {
      console.log(err)
    })
  }

  // 清除删除修改之后的副作用
  useEffect(() => {
    getUserInfo()
  }, []);

  // 获取后台数据
  const getUserInfo = () => {
    setTimeout(() => {
      axios.post(`${api}/getAllUser`).then(function (response) {
        setDataSource(response.data.data);
        setLoading(false);
      }).catch(function (error) {
        console.log(error)
      });
    }, 1000)
  }

  // 删除操作
  const Remove = (userId) => {
    axios.post(`${api}/deleteUser`, { userId }).then(response => {
      getUserInfo()
    }).catch(err => {
      console.log(err)
    })
  }

  const layout = {
    labelCol: {
      span: 8,
    },
    wrapperCol: {
      span: 16,
    },
  };

  const [form] = Form.useForm();

  const onFinish = (values) => {
    update(values)
    setIsModalOpen(false);
    getUserInfo()
  }

  const update = (values) => {
    axios.post(`${api}/updateUserInfo`, { values }).then(response => {
      console.log(response)
    }).catch(err => {
      console.log(err)
    })
  }

  return (
    <div className='table'>
      <Form>
        <Table
          bordered
          dataSource={dataSource}
          columns={columns}
          loading={loading}
          pagination={{
            pageSize: 5
          }}
          rowKey={(record) => record.userId} />
        <Modal title="修改用户信息" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
          <Form {...layout} form={form} name="userForm" onFinish={onFinish}>
            <Form.Item
              name="userId"
              hidden
              rules={[
                {
                  required: true,
                },
              ]}
            >
              <Input/>
            </Form.Item>
            <Form.Item
              name="username"
              label="用户名"
              rules={[
                {
                  required: true,
                },
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="address"
              label="水表安装地址"
              rules={[
                {
                  required: true,
                },
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="tel"
              label="电话"
              rules={[
                {
                  required: true,
                },
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="createTime"
              label="创建时间"
              rules={[
                {
                  required: true,
                },
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="state"
              label="账号状态"
              rules={[
                {
                  required: true,
                },
              ]}
            >
              <Input />
            </Form.Item>
            <Button type="primary" htmlType="submit" className='btn-sub'>
              保存修改
            </Button>
          </Form>
        </Modal>
      </Form>
    </div>
  )
}
